import re
import time
import telnetlib
from utils.log_ import setup_logger
import socket

logger = setup_logger(__file__)


class TelnetOlt:

    # 创建 Telnet 对象
    def __init__(self, telnet_host, telnet_username, telnet_password, telnet_port, telnet_timeout):
        self.host = telnet_host
        self.username = telnet_username
        self.password = telnet_password
        self.port = telnet_port
        self.timeout = telnet_timeout
        try:
            self.Tn = telnetlib.Telnet(host, port, timeout)
        except socket.timeout:
            logger.error(f'Telnet connection to {self.host}:{self.port} timed out')
            exit()
            # raise  # 重新抛出异常，以便调用者可以处理

    def read_until(self, pattern):
        output = self.Tn.read_until(pattern)
        # print(f'output = {output}')
        # 解码字节字符串为普通字符串
        output_str = output.decode('ascii')
        # 将 \r\n 替换为 \n
        output_str = output_str.replace('\r\n', '\n')
        logger.info(f'receive : \n{output_str}')
        return output_str

    def write(self, pattern):
        logger.info(f'send : \n{pattern}')
        self.Tn.write(pattern.encode('ascii') + b'\n')

    def login_olt(self):
        # 读取登录提示
        self.read_until(b'User name:')
        self.write(self.username)

        # 读取密码提示
        self.Tn.read_until(b'Password: ')
        self.write(self.password)

        self.read_until(b'>')
        self.write('enable')

        self.read_until(b'#')
        time.sleep(0.1)

        self.write('config')

        text = self.Tn.read_until(b'#')
        time.sleep(0.1)

        if b'(config)#' in text:
            return True
        else:
            return False

    def close(self):
        time.sleep(1)
        self.Tn.close()

    def get_cms_info(self):
        while True:
            self.write('show cms-connect info')
            out_put = self.read_until(b'(config)#')
            if ('Server-url' in out_put or 'Username' in out_put
                    or 'Password' in out_put or 'Status' in out_put):
                pass
            else:
                print(f'*****************************查看CMS infor telne接收异常, 重新尝试*****************************')
                print(f'output = {out_put}\n\n\n')
                time.sleep(1)
                continue
            # print(f'output = {out_put}')

            # 使用正则表达式查找匹配项
            matches = re.findall(r'(Server-url|Username|Password|Status)\s*:\s*(.*)', out_put, re.MULTILINE)

            # 创建一个字典来存储结果
            CmsInfo = {}
            for match in matches:
                key = match[0].strip()
                value = match[1].strip()
                CmsInfo[key] = value
            # print(f'CmsInfo = {CmsInfo}')
            # print(CmsInfo['Server-url'])
            # print(CmsInfo['Username'])
            # print(CmsInfo['Password'])
            # print(CmsInfo['Status'])

            return CmsInfo

    def check_cms_status(self):
        # 循环30s, 检测cms连接状态是否为connected
        for i in range(0, 30):
            tmp_cms_info = self.get_cms_info()
            # print(f'tmp_cms_info = {tmp_cms_info}')
            if tmp_cms_info['Status'] == 'Connected':
                return True
            # print('sleep 10 s')
            time.sleep(1)
        return False


if __name__ == '__main__':
    host = '192.168.4.126'
    username = 'root'
    password = 'admin'
    port = 23
    timeout = 5
    tn = TelnetOlt(host, username, password, port, timeout)

    if tn.login_olt():
        logger.info('login success')
    else:
        logger.info('login failed')

    cms_info = tn.get_cms_info()
    print(cms_info)

    tn.write('cms-connect server-url http://192.168.20.76:80/v1/bind#v=1&code=LX1QF3')
    tn.read_until(b'#')
    time.sleep(3)
    print(f'-------- --设置cms url完成----------------------------------------')
    time.sleep(10)

    if tn.check_cms_status():
        logger.info('cms connected')
    else:
        logger.info('cms connect failed')
    tn.close()
